<template>
  <div v-if="itemdata.lCanOutput === '1'">
    <template v-if="itemdata.sUIType == 'yearmonth'">
      <template v-if="itemdata.lMustInput === '1' && itemdata.lCanInput === '0'">
        <van-field :error="itemdata.sFormat?.length > 0" @change="changeDate" size="large" :id="itemdata.sField"
          v-model="itemdata.value" required placeholder="系统自动填充" readonly clearable :label="itemdata.sTitle"
          :error-message="itemdata.errormsg" @focus="iptFoucus" />
      </template>
      <template v-else-if="itemdata.lMustInput === '1'">
        <van-field :error="itemdata.sFormat?.length > 0" @change="changeDate" size="large" placeholder="请输入"
          :id="itemdata.sField" v-model="itemdata.value" required clearable :label="itemdata.sTitle"
          @click="openYearMonth(itemdata)" :error-message="itemdata.errormsg" @focus="iptFoucus" />
      </template>
      <template v-else-if="itemdata.lCanInput === '0'">
        <van-field :error="itemdata.sFormat?.length > 0" @change="changeDate" size="large" :id="itemdata.sField"
          v-model="itemdata.value" placeholder="系统自动填充" readonly clearable :label="itemdata.sTitle"
          :error-message="itemdata.errormsg" @focus="iptFoucus" />
      </template>
      <template v-else>
        <van-field :error="itemdata.sFormat?.length > 0" @change="changeDate" size="large" :id="itemdata.sField"
          v-model="itemdata.value" placeholder="请输入" readonly clearable :label="itemdata.sTitle"
          @click="openYearMonth(itemdata)" :error-message="itemdata.errormsg" @focus="iptFoucus" />
      </template>
    </template>
    <template v-else-if="ishead">
      <template v-if="itemdata.lMustInput === '1' && itemdata.lCanInput === '0'">
        <van-field :error="itemdata.sFormat?.length > 0" @change="changeDate" size="large" :id="itemdata.sField"
          v-model="itemdata.value" required placeholder="系统自动填充" readonly clearable :label="itemdata.sTitle"
          :error-message="itemdata.errormsg" @focus="iptFoucus" />
      </template>
      <template v-else-if="itemdata.lMustInput === '1'">
        <van-field :error="itemdata.sFormat?.length > 0" @change="changeDate" size="large" placeholder="请输入"
          :id="itemdata.sField" v-model="itemdata.value" required clearable :label="itemdata.sTitle"
          @click="openDatePicker(itemdata)" :error-message="itemdata.errormsg" @focus="iptFoucus" />
      </template>
      <template v-else-if="
        itemdata.lCanInput === '0' && itemdata.idObject == 'weekreports'
      ">
        <template v-if="itemdata.sField === 'bzjsrq'">
          <van-field :error="itemdata.sFormat?.length > 0" @change="changeDate" size="large" :id="itemdata.sField"
            v-model="bzjsrqField" placeholder="系统自动填充" readonly clearable :label="itemdata.sTitle"
            :error-message="itemdata.errormsg" @focus="iptFoucus" />
        </template>
        <template v-else-if="itemdata.sField === 'xzksrq'">
          <van-field :error="itemdata.sFormat?.length > 0" @change="changeDate" size="large" :id="itemdata.sField"
            v-model="xzksrqField" placeholder="系统自动填充" readonly clearable :label="itemdata.sTitle"
            :error-message="itemdata.errormsg" @focus="iptFoucus" />
        </template>
        <template v-else-if="itemdata.sField === 'xzjsrq'">
          <van-field :error="itemdata.sFormat?.length > 0" @change="changeDate" size="large" :id="itemdata.sField"
            v-model="xzjsrqField" placeholder="系统自动填充" readonly clearable :label="itemdata.sTitle"
            :error-message="itemdata.errormsg" @focus="iptFoucus" />
        </template>
        <template v-else>
          <van-field :error="itemdata.sFormat?.length > 0" @change="changeDate" size="large" :id="itemdata.sField"
            v-model="itemdata.value" disabled clearable :label="itemdata.sTitle" :error-message="itemdata.errormsg"
            @focus="iptFoucus" />
        </template>
      </template>
      <template v-else-if="
        itemdata.lCanInput === '0' && itemdata.idObject != 'weekreports'
      ">
        <van-field :error="itemdata.sFormat?.length > 0" @change="changeDate" size="large" :id="itemdata.sField"
          v-model="itemdata.value" placeholder="系统自动填充" readonly clearable :label="itemdata.sTitle"
          :error-message="itemdata.errormsg" @focus="iptFoucus" />
      </template>
      <template v-else>
        <van-field :error="itemdata.sFormat?.length > 0" @change="changeDate" size="large" :id="itemdata.sField"
          v-model="itemdata.value" placeholder="请输入" readonly clearable :label="itemdata.sTitle"
          @click="openDatePicker(itemdata)" :error-message="itemdata.errormsg" @focus="iptFoucus" />
      </template>
    </template>
    <template v-else>
      <template v-if="itemdata.lMustInput === '1' && itemdata.lCanInput === '0'">
        <van-field :error="itemdata.sFormat?.length > 0" @change="changeDate" size="large"
          :id="index + '_' + itemdata.sField" v-model="itemdata.value" required placeholder="系统自动填充" readonly clearable
          :label="itemdata.sTitle" :error-message="itemdata.errormsg" @focus="iptFoucus" />
      </template>
      <template v-else-if="itemdata.lMustInput === '1'">
        <van-field :error="itemdata.sFormat?.length > 0" @change="changeDate" size="large" placeholder="请输入"
          :id="index + '_' + itemdata.sField" v-model="itemdata.value" required clearable readonly
          :label="itemdata.sTitle" @click="openDatePicker(itemdata)" :error-message="itemdata.errormsg"
          @focus="iptFoucus" />
      </template>
      <template v-else-if="itemdata.lCanInput === '0'">
        <van-field :error="itemdata.sFormat?.length > 0" @change="changeDate" size="large"
          :id="index + '_' + itemdata.sField" v-model="itemdata.value" placeholder="系统自动填充" readonly clearable
          :label="itemdata.sTitle" :error-message="itemdata.errormsg" @focus="iptFoucus" />
      </template>
      <template v-else>
        <van-field :error="itemdata.sFormat?.length > 0" @change="changeDate" size="large" placeholder="请输入"
          :id="index + '_' + itemdata.sField" readonly v-model="itemdata.value" clearable :label="itemdata.sTitle"
          @click="openDatePicker(itemdata)" :error-message="itemdata.errormsg" @focus="iptFoucus" />
      </template>
    </template>
    <van-popup v-model="datepickershow" round position="bottom">
      <van-datetime-picker v-model="currentDate" type="date" @confirm="selectedDate" :min-date="minDate" />
    </van-popup>
    <van-popup v-model="datetimeshow" round position="bottom">
      <van-datetime-picker v-model="currentDate" type="datetime" @confirm="selectedDateTime" />
    </van-popup>
    <van-popup v-model="yearmonthshow" round position="bottom">
      <van-datetime-picker v-model="currentYearMonth" type="year-month" @confirm="selectedYearMonth" />
    </van-popup>
  </div>
</template>
<script>
import { Toast } from 'vant'

export default {
  data() {
    return {
      isRed: '',
      minDate: new Date(1900, 0, 1),
      yearmonthshow: false,
      currentYearMonth: new Date(),
      datepickershow: false,
      datetimeshow: false,
      clickmodel: {},
      currentDate: new Date(),
    };
  },
  props: {
    bzjsrqField: {
      type: String,
      required: false,
    },
    xzksrqField: {
      type: String,
      required: false,
    },
    xzjsrqField: {
      type: String,
      required: false,
    },
    itemdata: {
      type: Object,
      required: false,
    },
    ishead: {
      type: Boolean,
      default: false,
    },
    index: {
      type: Number,
      required: false,
    },
    jsondata: {
      type: Object,
      required: false,
    },
  },
  mounted() {
    if (
      this.itemdata.idObject === "hdsqd" 
    ) {
      let date = "";
      for (let groupindex in this.jsondata.head) {
        for (let itemindex in this.jsondata.head[groupindex].groupvalue) {
          let item = this.jsondata.head[groupindex].groupvalue[itemindex];
          if (item.sField === "date") {
            date = item.value;
          }
        }
      }
      let time = date.split('-')
      this.minDate = new Date(time[0], time[1] - 1, time[2])
    }
    this.isRed = this.itemdata?.sFormat.split(';').filter(i => {
      return i == 'fontcolor:red'
    })[0]?.split(':')[1]
  },
  watch: {
    "itemdata.value": {
      immediate: true, //开启立即监听
      handler(v) {
        let traMonth = v.split("-")[1];
        traMonth =
          parseInt(traMonth, 10) < 10 ? traMonth.replace(/^0+/, "") : traMonth;
        this.itemdata.copyTitle = this.itemdata.sTitle;
        this.$emit("dateChange", this.itemdata, Number(traMonth));
      },
    },
    jsondata: {
      immediate: true, //开启立即监听
      deep: true, //开启立即监听
      handler(v, o) {
        if (this.$route.query.idobject === "accountsbgd") {
          let qxotckhbq;
          let xzotckhb;
          let edate
          let enddate
          for (let groupindex in v.head) {
            for (let itemindex in v.head[groupindex].groupvalue) {
              let item = v.head[groupindex].groupvalue[itemindex];
              if (item.sField === "edate") {
                edate = item.value;
              }
              if (item.sField === "enddate") {
                enddate = item.value;
              }
            }
          }
          for (let groupindex in v.head) {
            for (let itemindex in v.head[groupindex].groupvalue) {
              let item = v.head[groupindex].groupvalue[itemindex];
              if (item.sField === "qxotckhbq") {
                qxotckhbq = item.valuehidden;
              }
              if (item.sField === "xzotckhbq") {
                xzotckhb = item.valuehidden;
              }
            }
          }
          let date;
          let xzstartDate;
          let xzendDate;
          if (qxotckhbq && xzotckhb) {
            const lastDayOfLastMonth = new Date();
            lastDayOfLastMonth.setDate(0);
            date = this.formatDate2(lastDayOfLastMonth);
          } else if (qxotckhbq) {
            const lastDayOfThisMonth = new Date();
            lastDayOfThisMonth.setMonth(lastDayOfThisMonth.getMonth() + 1, 0);
            date = this.formatDate2(lastDayOfThisMonth);
          }
          for (let groupindex in v.head) {
            for (let itemindex in v.head[groupindex].groupvalue) {
              let item = v.head[groupindex].groupvalue[itemindex];
              if (item.sField === "enddate" && !enddate) {
                item.value = date;
              }
              if (xzotckhb) {
                if (item.sField === "sdate") {
                  item.value = '审批终审时间当月1号';
                }
                if (item.sField === "edate" && !edate) {
                  item.value = '2099-12-31';
                }
              }
            }
          }
        }
        // if (
        //   this.itemdata.idObject === "hdsqd"
        // ) {
        //   let jhkssj = "";
        //   let date = "";
        //   for (let groupindex in this.jsondata.head) {
        //     for (let itemindex in this.jsondata.head[groupindex].groupvalue) {
        //       let item = this.jsondata.head[groupindex].groupvalue[itemindex];
        //       if (item.sField === "jhkssj") {
        //         jhkssj = item.value;
        //       } else if (item.sField === "date") {
        //         date = item.value;
        //       }
        //     }
        //   }
        //   const d1 = new Date(jhkssj);
        //   const d2 = new Date(date);

        //   const result = d1 - d2; // 返回毫秒差
        //   console.log(result, jhkssj, date)
        //   if (result < 0) {
        //     Toast("计划开始时间不可以在单据日期之前！");
        //     this.itemdata.value = date
        //     return;
        //   }
        // }

      },
    },
  },
  methods: {
    formatDate2(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0"); // 月份是从0开始的，所以要加1，并确保是两位数
      const day = String(date.getDate()).padStart(2, "0");
      return `${year}-${month}-${day}`;
    },
    changeDate() { },
    iptFoucus() {
      // document.activeElement.blur()
    },
    openDatePicker(datamodel) {
      if (
        datamodel.value != null &&
        datamodel.value !== undefined &&
        datamodel.value !== ""
      ) {
        if (datamodel.sUITypeExp !== "long") {
          datamodel.value = datamodel.value.substring(0, 10);
        }
        let newDate = new Date(datamodel.value.replace(/-/g, "/"));
        this.currentDate = new Date(newDate);
      }
      this.clickmodel = datamodel;
      if (datamodel.sUITypeExp === "long") {
        this.datetimeshow = true;
      } else {
        this.datepickershow = true;
      }
    },
    selectedDate() {
      // Toast('111"' + JSON.stringify(this.clickmodel))
      //console.log(this.currentDate)
      let year = this.currentDate.getFullYear(); // 获取完整的年份(4位,1970-????)
      let month = this.currentDate.getMonth(); // 获取当前月份(0-11,0代表1月)
      let day = this.currentDate.getDate(); // 获取当前日(1-31)

      if (this.clickmodel.idObject === "weekreports") {
        // 设置 本周开始日期
        this.clickmodel.value = this.getWeekStartDate(year, month, day);
        // 设置 本周结束日期
        this.$emit("update:bzjsrqField", this.getWeekEndDate(year, month, day));
        // 设置 下周开始日期
        this.$emit(
          "update:xzksrqField",
          this.getNextWeekStartDate(year, month, day)
        );
        // 设置 下周结束日期
        this.$emit(
          "update:xzjsrqField",
          this.getNextWeekEndDate(year, month, day)
        );
      } else {
        month += 1;
        if (month < 10) {
          month = "0" + month;
        }
        if (day < 10) {
          day = "0" + day;
        }
        let dateString = year + "-" + month + "-" + day;

        this.clickmodel.errormsg = "";
        this.clickmodel.value = dateString;
      }



      this.datepickershow = false;
    },
    selectedDateTime() {
      //console.log(this.currentDate)
      let year = this.currentDate.getFullYear(); // 获取完整的年份(4位,1970-????)
      let month = this.currentDate.getMonth() + 1; // 获取当前月份(0-11,0代表1月)
      let day = this.currentDate.getDate(); // 获取当前日(1-31)
      let hour = this.currentDate.getHours();
      let minute = this.currentDate.getMinutes();
      if (month < 10) {
        month = "0" + month;
      }
      if (day < 10) {
        day = "0" + day;
      }
      if (hour < 10) {
        hour = "0" + hour;
      }
      if (minute < 10) {
        minute = "0" + minute;
      }
      let dateString =
        year + "-" + month + "-" + day + " " + hour + ":" + minute + ":00";
      this.clickmodel.value = dateString;
      this.clickmodel.errormsg = "";
      this.datetimeshow = false;
    },
    // 获得本周的开始日期
    getWeekStartDate(y, m, d) {
      var now = new Date(y, m, d); // 当前日期

      var nowDayOfWeek = now.getDay() || 7; // 今天本周的第几天
      var nowDay = now.getDate(); // 当前日
      var nowMonth = now.getMonth(); // 当前月
      var nowYear = now.getFullYear(); // 当前年
      var weekStartDate = new Date(
        nowYear,
        nowMonth,
        nowDay - nowDayOfWeek + 1
      );
      return this.formatDate(weekStartDate);
    },
    // 获得本周的结束日期
    getWeekEndDate(y, m, d) {
      return this.formatDate(this.getWeekEndDateObj(y, m, d));
    },
    getWeekEndDateObj(y, m, d) {
      var now = new Date(y, m, d); // 当前日期
      var nowDayOfWeek = now.getDay() || 7; // 今天本周的第几天

      var nowDay = now.getDate(); // 当前日
      var comp = nowDay + 7 - nowDayOfWeek;
      // 周日就不用加了
      if (nowDayOfWeek === 0) {
        comp = nowDay;
      }

      var nowMonth = now.getMonth(); // 当前月
      var nowYear = now.getFullYear(); // 当前年

      var weekEndDate = new Date(nowYear, nowMonth, comp);

      return weekEndDate;
    },
    getNextWeekStartDate(y, m, d) {
      return this.formatDate(this.getNextWeekStartDateObj(y, m, d));
    },
    getNextWeekStartDateObj(y, m, d) {
      let date = this.getWeekEndDateObj(y, m, d);
      date.setDate(date.getDate() + 1);
      return date;
    },
    getNextWeekEndDate(y, m, d) {
      let date = this.getWeekEndDateObj(y, m, d);
      date.setDate(date.getDate() + 7);
      return this.formatDate(date);
    },
    // 格式化日期：yyyy-MM-dd
    formatDate(date) {
      var myyear = date.getFullYear();
      var mymonth = date.getMonth() + 1;
      var myweekday = date.getDate();

      if (mymonth < 10) {
        mymonth = "0" + mymonth;
      }
      if (myweekday < 10) {
        myweekday = "0" + myweekday;
      }
      return myyear + "-" + mymonth + "-" + myweekday;
    },
    openYearMonth(datamodel) {
      if (
        datamodel.value != null &&
        datamodel.value !== undefined &&
        datamodel.value !== ""
      ) {
        datamodel.value = datamodel.value.substring(0, 7);
        this.currentYearMonth = new Date(datamodel.value);
      }
      this.clickmodel = datamodel;
      this.yearmonthshow = true;
    },
    selectedYearMonth() {
      console.log(222222222);
      //console.log(this.currentYearMonth)
      let year = this.currentYearMonth.getFullYear();
      let month = this.currentYearMonth.getMonth() + 1;
      if (month < 10) {
        month = "0" + month;
      }
      let datestring = year + "-" + month;
      this.clickmodel.value = datestring;
      this.clickmodel.errormsg = "";
      this.yearmonthshow = false;
      console.log(month);
      let traMonth = this.currentYearMonth.getMonth() + 1;
      // this.$emit('dateChange',this.itemdata, traMonth)
    },
  },
  activated() { },
};
</script>
